// V-backend/src/models/Anchor.js
const { DataTypes } = require('sequelize');

module.exports = (sequelize) => {
  const Anchor = sequelize.define('Anchor', {
    anchor_id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      field: 'anchor_id'
    },
    anchor_name: {
      type: DataTypes.STRING(50),
      allowNull: false,
      field: 'anchor_name'
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: false,
      unique: true,
      field: 'email'
    },
    password: {
      type: DataTypes.STRING(255),
      allowNull: false,
      field: 'password'
    },
    gender: {
      type: DataTypes.ENUM('male', 'female', 'unknown'),
      defaultValue: 'unknown',
      field: 'gender'
    },
    avatar: {
      type: DataTypes.STRING(255),
      defaultValue: '/src/assets/images/avatars/default-avatar.png',
      field: 'avatar'
    },
    anchor_info: {
      type: DataTypes.TEXT,
      field: 'anchor_info'
    },
    role: {
      type: DataTypes.ENUM('super_admin', 'anchor'),
      defaultValue: 'anchor',
      field: 'role'
    }
  }, {
    tableName: 'v_anchor',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    hooks: {
      beforeCreate: async (anchor) => {
        if (anchor.password) {
          const bcrypt = require('bcryptjs');
          anchor.password = await bcrypt.hash(anchor.password, 10);
        }
      },
      beforeUpdate: async (anchor) => {
        if (anchor.changed('password')) {
          const bcrypt = require('bcryptjs');
          anchor.password = await bcrypt.hash(anchor.password, 10);
        }
      }
    }
  });

  // 添加实例方法
  Anchor.prototype.toSafeObject = function() {
    const { password, ...safeData } = this.toJSON();
    return safeData;
  };

  // 关联定义
  Anchor.associate = function(models) {
    Anchor.hasMany(models.Activity, {
      foreignKey: 'anchor_id',
      as: 'activities'
    });
  };

  return Anchor;
};